"""Top-level workflow controller for Memetic Algorithm execution and GUI interaction.

This module handles the high-level execution flow of the Memetic Algorithm, including:
- Configuration handling
- Data loading and preprocessing
- Algorithm initialization
- Results processing
- GUI interactions
"""

import sys
from pathlib import Path
import datetime
import json

from UAS.algorithm.memetic import MemeticAlgorithm
from UAS.data.graph_builder import GraphBuilder
from UAS.data.excel_parser import ExcelParser


class MemeticWorkflow:
    def __init__(self, config_path=None):
        """Initialize the workflow controller.
        
        :param config_path: Path to configuration file containing algorithm parameters
        """
        self.config = self.loadDefaultConfig()
        if config_path:
            self.loadConfig(config_path)
            
    def loadDefaultConfig(self):
        """Load default configuration."""
        return {
            'population_size': 10,
            'max_iterations': 10,
            'max_mutation_prob': 0.2,
            'min_mutation_prob': 0.001,
            'time_limit': 120,
            'valid_time': 150,
            'penalty_interval': 10,
            'penalty_rate': 10,
            'data_path': 'd:/Work/Projects/orienteering/UAS/',
            'performance_mode': False  # 是否启用高性能模式
        }
    
    def loadConfig(self, config_path):
        """Load configuration from file."""
        # Implement configuration file loading logic
        pass
    
    def load_data(self):
        """加载必要的数据文件"""
        # 从配置获取文件路径
        points_path = self.config.get('points_path')
        matrix_path = self.config.get('matrix_path')
        
        if not points_path or not matrix_path:
            raise ValueError("未设置有效的文件路径")
        if not Path(points_path).exists():
            raise FileNotFoundError(f"点位文件不存在: {points_path}")
        if not Path(matrix_path).exists():
            raise FileNotFoundError(f"矩阵文件不存在: {matrix_path}")
            
        # 使用动态路径初始化解析器
        parser = ExcelParser(points_path, matrix_path)
        parser.load_data()
        builder = GraphBuilder(parser)
        
        return builder.build_graph()
    
    def initialize_algorithm(self, valid_points, profits, valid_matrix, node_mapping):
        """Initialize the MemeticAlgorithm with configuration parameters."""
        return MemeticAlgorithm(
            valid_points=valid_points,
            valid_matrix=valid_matrix,
            node_mapping=node_mapping,
            profits=profits,
            population_size=self.config['population_size'],
            max_iterations=self.config['max_iterations'],
            max_mutation_prob=self.config['max_mutation_prob'],
            min_mutation_prob=self.config['min_mutation_prob'],
            penalty_interval=self.config['penalty_interval'],
            penalty_rate=self.config['penalty_rate'],
            time_limit=self.config['time_limit'],
            valid_time=self.config['valid_time'],
            performance_mode=self.config['performance_mode']
        )
    
    def run_algorithm(self, algorithm):
        """Execute the MemeticAlgorithm process."""
        return algorithm.run()
    
    def process_results(self, final_population):
        """Process and visualize results."""
        if final_population:
            # Convert SortedList to regular list
            population_list = list(final_population)
            
            # Format all solutions
            results = [{
                'sequence': c.sequence,
                'total_profit': c.total_profit,
                'total_cost': c.total_cost
            } for c in population_list]
            
            # Create results directory if not exists
            results_path = Path('results')
            results_path.mkdir(exist_ok=True)

            return population_list
        else:
            print("未找到有效解")
            return None
            
    def terminate(self):
        """Terminate the running workflow."""
        if hasattr(self, 'algorithm'):
            self.algorithm.terminate()

    def run_workflow(self):
        """Execute complete workflow."""
        if not self.config['performance_mode']:
            print("=== 开始执行工作流 (详细模式) ===")
        else:
            print("=== 开始执行工作流 (高性能模式) ===")
        
        try:
            # Load data
            valid_points, profits, valid_matrix, node_mapping = self.load_data()
            if not self.config['performance_mode']:
                print("数据加载成功")
            
            # Initialize algorithm
            self.algorithm = self.initialize_algorithm(valid_points, profits, 
                                               valid_matrix, node_mapping)
            if not self.config['performance_mode']:
                print("算法初始化完成")
        
            # Run algorithm
            final_population = self.algorithm.run()
            if not self.config['performance_mode']:
                print("算法执行完成")
            
            # Process results
            results = self.process_results(final_population)
            if not self.config['performance_mode']:
                print("结果处理完成")
            
        except Exception as e:
            print(f"执行出错: {str(e)}")
            return None
            
        return results
    
def main():
    """独立运行的工作流执行函数"""
    # 初始化工作流
    workflow = MemeticWorkflow()
    
    # 配置算法参数
    workflow.config.update({
        'points_path': 'd:/Work/Projects/UAS/valid_points - Tsiligirides 1.xlsx',
        'matrix_path': 'd:/Work/Projects/UAS/valid_matrix - Tsiligirides 1.xlsx',
        'data_path': 'd:/Work/Projects/UAS/',
        'population_size': 50,
        'max_iterations': 40,
        'max_mutation_prob': 0.1,
        'min_mutation_prob': 0.01,
        'time_limit': 600,
        'valid_time': 600,
        'penalty_interval': 10,
        'penalty_rate': 10,
        'performance_mode': False  # 设置为True启用高性能模式
    })
    
    print("=== 开始执行算法 ===")
    start_time = datetime.datetime.now()
    
    try:
        # 执行工作流
        results = workflow.run_workflow()
        
        if results:
            print("\n=== 算法执行完成 ===")
            print(f"最优解: 总收益={results[0].total_profit}, 总耗时={results[0].total_cost}")
            
            # 保存结果到JSON文件
            results_dir = Path('d:/Work/Projects/UAS/results/')
            results_dir.mkdir(exist_ok=True)
            
            result_file = results_dir / f"results_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
            with open(result_file, 'w') as f:
                json.dump([{
                    'sequence': r.sequence,
                    'total_profit': r.total_profit,
                    'total_cost': r.total_cost
                } for r in results], f, indent=2)
            
            print(f"结果已保存至: {result_file}")
        else:
            print("未找到有效解")
            
    except Exception as e:
        print(f"\n!!! 执行出错: {str(e)}")
    
    end_time = datetime.datetime.now()
    print(f"\n总执行时间: {(end_time - start_time).total_seconds():.2f}秒")

if __name__ == "__main__":
    main()
